Visualizing `<<`, `>>`, and `>>>`.
The **left shift (`<<`)** operator shifts the bits of the first operand to the left by the number of positions specified by the second operand. Zeroes are shifted in from the right. This is equivalent to multiplying by powers of 2.
5 << 1; // 10 (binary 0101 -> 1010)
Initial Binary:
Shifted Binary:
Result (Decimal):
The **signed right shift (`>>`)** operator shifts the bits of the first operand to the right. The sign bit (most significant bit) is propagated, meaning the sign of the number is preserved. This is equivalent to integer division by powers of 2.
10 >> 1; // 5 (binary 1010 -> 0101) -10 >> 1; // -5 (binary ...10110 -> ...1011)
Initial Binary:
Shifted Binary:
Result (Decimal):
The **unsigned right shift (`>>>`)** operator shifts the bits of the first operand to the right. Zeroes are shifted in from the left, regardless of the sign of the original number. This operator always produces a non-negative result for positive numbers and can convert negative numbers to large positive numbers.
10 >>> 1; // 5 (binary 1010 -> 0101) -10 >>> 1; // 2147483643 (binary ...10110 -> 01...01011)
Initial Binary:
Shifted Binary:
Result (Decimal):